//
//  SearchViewController.m
//  DanTang
//
//  Created by honeyrr on 2017/9/11.
//  Copyright © 2017年 honeyrr. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchTableViewCell.h"

@interface SearchViewController ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource>
//搜索条
@property(nonatomic,strong) UISearchBar *sb;

@property(nonatomic,strong) UITableView *searchTableView;

@property(nonatomic,strong) NSMutableArray *dataArr;
@end

@implementation SearchViewController

//懒加载
-(UISearchBar *)sb
{
    if (!_sb) {
        _sb = [[UISearchBar alloc]init];
        _sb.placeholder = @"搜索商品、标题";
        _sb.showsCancelButton = YES;
    }
    return _sb;
}

//界面即将出现
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //默认编辑状态
    [self.sb becomeFirstResponder];
}

//界面即将消失
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.sb resignFirstResponder];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.dataArr = [NSMutableArray new];
    
    [self initView];
    [self setNavBar];
    
}
-(void)initView
{
    self.searchTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    self.searchTableView.delegate = self;
    self.searchTableView.dataSource = self;
    self.searchTableView.tableHeaderView = [self headerView];
    self.searchTableView.tableFooterView = [UIView new];
    [self.view addSubview:self.searchTableView];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_dataArr.count == 0) {
        self.searchTableView.tableHeaderView.hidden = YES;
    } else {
        self.searchTableView.tableHeaderView.hidden = NO;
    }
    return self.dataArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"searchCell";
    SearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[SearchTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    [cell.shopImgView setImageWithURL:self.dataArr[indexPath.row][@"cover_image_url"] placeholderImage:[UIImage imageNamed:@"PlaceHolderImage_small_31x26_"]];
    cell.shopName.text = self.dataArr[indexPath.row][@"name"];
    cell.shopRMB.text = [NSString stringWithFormat:@"￥%@",self.dataArr[indexPath.row][@"price"]];
    cell.shopLikes.text = [NSString stringWithFormat:@"%@",self.dataArr[indexPath.row][@"likes_count"]];
    cell.shopDetail.text = self.dataArr[indexPath.row][@"description"];
    return cell;
}

-(UIView *)headerView
{
    NSArray *arr = @[@"默认排序", @"热度排序", @"价格高-低", @"价格低-高"];
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 24)];
    headerView.backgroundColor = MRNavTabRGBColor;
    CGFloat btnWidth = (self.view.frame.size.width - 25) / arr.count;
    
    for (int i = 0; i < arr.count; i++) {
        UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(i * btnWidth, 0, btnWidth, 24)];
        [button setTitle:arr[i] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        button.tag = i;
        [headerView addSubview:button];
        
        [button addTarget:self action:@selector(sortType:) forControlEvents:UIControlEventTouchUpInside];
    }
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width - 25, 0, 25, 24)];
    [btn setBackgroundImage:[UIImage imageNamed:@"tableview_loading"] forState:UIControlStateNormal];
    [headerView addSubview:btn];
    [btn addTarget:self action:@selector(cutTableView:) forControlEvents:UIControlEventTouchUpInside];
    return headerView;
}

-(void)sortType:(UIButton *)sender
{
    NSInteger tag = sender.tag;
    NSArray *sortURLArr = @[@"", @"hot", @"price%3Adesc", @"price%3Aasc"];
    NSLog(@"sortURLArr_____> %@",sortURLArr[tag]);
    [self laodNewInfo:self.sb.text sortType:sortURLArr[tag]];
    
}

-(void)cutTableView:(UIButton *)sender
{
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.searchTableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 128;
}

//设置导航条
-(void)setNavBar
{
    self.navigationItem.titleView = self.sb;
    self.sb.delegate = self;
}

//设置请求
-(void)laodNewInfo:(NSString *)word sortType:(NSString *)type
{
    NSString *urlString = [NSString stringWithFormat:@"http://api.dantangapp.com/v1/search/item?keyword=%@&limit=20&offset=0&sort=%@",word,type];
    [[DTNetWork sharedNetWork] loadDataInfo:urlString parameters:nil success:^(id  _Nullable responseObject) {
        if ([responseObject[@"code"] integerValue] == 200) {
            [self.dataArr removeAllObjects];
            [self.dataArr addObjectsFromArray:responseObject[@"data"][@"items"]];
            NSLog(@"----> %@",responseObject[@"data"][@"items"]);
        } else {
            NSLog(@"----->加载失败");
        }
        [self.searchTableView reloadData];
    } failure:^(NSError * _Nullable error) {
        NSLog(@"错误");
    }];
}

#pragma mark - <UISearchBarDelegate>
//搜索结束代理
-(BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    return YES;
}
//当点击search按钮触发的代理
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    //第一响应：回收键盘
    [self.sb resignFirstResponder];
    //判断搜索内容
    if (self.sb.text.length > 0) {
        //有输入
        //调用网络连接
        //[self laodNewInfo:searchBar.text sortType:@""];
    } else {
        //无输入，直接结束
        return;
    }
}
//返回按钮的代理
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [self.navigationController popViewControllerAnimated:YES];
}
//搜索代理
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    //判断搜索输入的内容是否为空
    if (searchText.length > 0) {
//        [self.dataArr removeAllObjects];
        [self laodNewInfo:searchText sortType:@""];
    } else {
        [self.dataArr removeAllObjects];
    }
    [self.searchTableView reloadData];
}

#pragma mark - 当滑动tableview，关闭软键盘
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}


@end
